#!/usr/bin/env bash

set -e
set -o pipefail

ENV_NAME="crypto_tool"
INSTALL_PATH="$HOME/miniconda"
CONDA_BIN="$INSTALL_PATH/bin/conda"

# Conda 安装
if ! command -v conda &> /dev/null; then
    echo "[INFO] Conda not found. Downloading and installing Miniconda..."

    wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh

    if [ -d "$INSTALL_PATH" ]; then
        echo "[WARNING] $INSTALL_PATH already exists, updating Miniconda..."
        bash miniconda.sh -u -b -p "$INSTALL_PATH"
    else
        echo "[INFO] Installing fresh Miniconda to $INSTALL_PATH..."
        bash miniconda.sh -b -p "$INSTALL_PATH"
    fi

    # 配置 conda 命令
    echo "[INFO] Linking conda to /usr/local/bin/conda"
    sudo ln -sf "$CONDA_BIN" /usr/local/bin/conda

    echo "[INFO] Writing init script to /etc/profile.d/conda-init.sh"
    echo "eval \"\$($INSTALL_PATH/bin/conda shell.bash hook)\"" | sudo tee /etc/profile.d/conda-init.sh > /dev/null
    sudo chmod +x /etc/profile.d/conda-init.sh

    echo "[INFO] Configuring Tsinghua mirror"
    "$CONDA_BIN" config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
    "$CONDA_BIN" config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
    "$CONDA_BIN" config --set show_channel_urls yes
else
    echo "[INFO] Conda already installed, skipping installation"
fi

# 创建环境
if ! conda env list | grep -q "^$ENV_NAME "; then
    echo "[INFO] Creating conda environment: $ENV_NAME"
    conda create -y -n "$ENV_NAME" python=3.10.12
else
    echo "[INFO] Conda environment $ENV_NAME already exists"
fi

# 安装依赖
echo "[INFO] Installing Python dependencies..."
conda run -n "$ENV_NAME" pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

echo "[SUCCESS] Setup completed!"
